<script lang="ts" setup>
import { h, reactive, useTemplateRef } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import XyIcon from '@/components/XyIcon'

const searchMethod = async (searchData: SearchData, pageData: PageData) => {
  pageData.loading = true
  ElMessage.success(JSON.stringify(searchData))
  await new Promise(r => setTimeout(r, 500))
  pageData.loading = false
  pageData.total = 3
  pageData.tableData = tableData
}

const tableSortRef = useTemplateRef('tableSortRef')
const clearSortSex = () => {
  tableSortRef.value?.tableRef?.sortClearCondition?.('sex')
}
const clearSortAge = () => {
  tableSortRef.value?.tableRef?.sortClearCondition?.('age')
}
const clearSortAll = () => {
  tableSortRef.value?.tableRef?.sortClearCondition?.()
}
interface Student {
  name: string
  age: number
  sex: string
}
const tableData = reactive<Student[]>([
  {
    name: '王五',
    age: 20,
    sex: '男'
  },
  {
    name: '张三',
    age: 18,
    sex: '女'
  },
  {
    name: '李四',
    age: 19,
    sex: '男'
  }
])
const tableConfigSort = reactive<TableConfig<Student>>({
  columns: [
    { type: 'default', label: '姓名（前端）', prop: 'name', sortable: true },
    {
      type: 'default',
      label: '年龄（前端）',
      prop: 'age',
      sortable: true,
      sortOrders: ['descending', 'ascending', 'none'],
      sortOper: (a, b, sortKey) => {
        if (sortKey === 'descending') return b.age - a.age
        return a.age - b.age
      }
    },
    {
      type: 'default',
      label: '性别（后端）',
      prop: 'sex',
      propAlias: 'sex123',
      sortable: 'searchMethod',
      sortIcon: () => h(XyIcon, { style: { fontSize: '16px' }, icon: 'tabler:sort-descending-2-filled' })
    }
  ]
})
</script>
<template>
  <ElButton @click="clearSortSex">清空性别排序</ElButton>
  <ElButton @click="clearSortAge">清空年龄排序</ElButton>
  <ElButton @click="clearSortAll">清空全部排序</ElButton>
  <XyTable ref="tableSortRef" :tableConfig="tableConfigSort" @search-method="searchMethod" />
</template>
